<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文字雨</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      html,
      body {
        height: 100%;
      }

      body {
        background-color: #000;
        overflow: hidden;
      }

      #canvas {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>

  <body>
    <canvas id="canvas"></canvas>

    <script>
      const canvas = document.getElementById('canvas')
      const ctx = canvas.getContext('2d')
      // 文字大小
      const fontSize = 16 * devicePixelRatio
      // 文字颜色
      const fontColoen = '#6BE445'
      // 文字x偏移
      const fontXOffset = fontSize / 2

      // 初始化
      function init() {
        // 设置宽高
        canvas.width = window.innerWidth * devicePixelRatio
        canvas.height = window.innerHeight * devicePixelRatio

        // 设置文字对其方式
        ctx.textAlign = 'left'
        ctx.textBaseline = 'top'

        // 设置文字大小
        ctx.font = `${fontSize}px "Roboto Mono"`
      }

      // 获取随机字符
      function getReandomChar() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        return chars[Math.floor(Math.random() * chars.length)]
      }

      init()

      // 列数
      const columnCount = Math.floor(canvas.width / fontSize)
      const charIndex = new Array(columnCount).fill(0)

      // 绘制
      function draw() {
        // 填充画布
        ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
        ctx.fillRect(0, 0, canvas.width, canvas.height)

        ctx.fillStyle = fontColoen
        for (let i = 0; i < columnCount; i++) {
          const text = getReandomChar()

          const x = i * fontSize + fontXOffset
          const y = charIndex[i] * fontSize
          ctx.fillText(text, x, y)

          // 随机量
          const random = Math.random() > 0.98

          if (y > canvas.height && random) {
            charIndex[i] = 0
          } else {
            charIndex[i]++
          }
        }
      }

      setInterval(draw, 50)
    </script>
  </body>
</html>
